package com.killer_jin.core.common.util.api;

import com.killer_jin.core.common.exception.AuthFaildException;
import com.killer_jin.core.common.util.vo.ApiUser;
import org.springframework.stereotype.Component;

/**
 * 仅使用在api的controller中!
 * Created by Frank Wu on 16/4/29.
 */
@Component
public class ApiUserHolder {
    private static ThreadLocal<ApiUser> users = new ThreadLocal<>();
    private static ThreadLocal<String> authError = new ThreadLocal<>();

    /**
     * 注意如果项目中用到了线程池,必须在退出或者初始化的时候把信息重制为空
     */
    public void setUser(ApiUser user) {
        users.set(user);
    }

    public ApiUser getUser() {
        return users.get();
    }


    /**
     * 判断登录
     */
    public void assertUserExists() {
        if (users.get() == null) {
            String msg = authError.get();
            msg = msg != null ? msg : "请先登录";
            throw new AuthFaildException(msg);
        }
    }

    /**
     * 注意如果项目中用到了线程池,必须在退出或者初始化的时候把信息重置为空
     */
    public void setErrorMsg(String error) {
        authError.set(error);
    }
}
